package JUC_stady;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Project: tobe-better-coder
 * Package: JUC_stady
 *
 * @author : Mr.xu
 * @date : 2023/3/21 22:15
 */
public class CASDemo {


    public static void main(String[] args) {
        method();
    }

    /**
     * 手写自旋锁
     */
    public static void method() {
        Test test = new Test();
        new Thread(() -> {

            test.lock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            test.unlock();
        }, "t1").start();

//        try { TimeUnit.MILLISECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); }
//        new Thread(() ->{
//            com.test.lock();
//            com.test.unlock();
//        },"t2").start();
    }
}

class Test {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock() {
        System.out.println(Thread.currentThread().getName() + "进来加锁了");
        Thread thread = Thread.currentThread();
        while (!atomicReference.compareAndSet(null, thread)) ;
        {
            System.out.println(Thread.currentThread().getName() + "进入等待");
            try {
                TimeUnit.SECONDS.sleep(1);//增加时间减少
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "加锁成功");
    }

    public void unlock() {
        System.out.println(Thread.currentThread().getName() + "进来解锁了");
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);//这句代码意义就是释放这把锁了
    }
}